package com.aspose.words.maven.wizard;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;

import com.aspose.words.maven.wizard.ResourceFactory.AsposeWizardResources;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import freemarker.template.Template;

class MavenProjectGenerationUtility{

	private IFolder tempFolder;
	private JsonObject tempJO;
	
	/**
		This method recursively generate the folder structure based on pattern defined in file "maven_project_structure.ftl"
	 * @param project
	 * @param path
	 * @param node
	 */
	void generateDirectoryStructure(IProject project, StringBuilder path, JsonObject node){
		String parentPath = path.toString();//Parent Path
		for(Entry<String, JsonElement> entry : node.entrySet()){
			path = new StringBuilder(parentPath);
			try {
				tempFolder = project.getFolder(path.append(entry.getKey() + "/").toString());
				tempFolder.create(true, true, null);
				tempJO = (JsonObject) entry.getValue();
				generateDirectoryStructure(project, path, tempJO);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
	}
	
	void generateJavaPackages(IJavaProject ijp, IFolder sourceFolder, String packageName){
		IPackageFragmentRoot ipfr = ijp.getPackageFragmentRoot(sourceFolder);
		try {
			ipfr.createPackageFragment(packageName, true, null);
		} catch (JavaModelException e) {
			e.printStackTrace();
		}
	}
	
	void generatePomFile(IProject iProject, String groupId, String artifactId, String version){
		Map<String, String> rootMap = new LinkedHashMap<>();
//			Preparing Maven Project Coordinates
		rootMap.put("groupId", groupId);//Group Id
		rootMap.put("artifactId", artifactId);//Artifact Id
		rootMap.put("version", version);//Version
		final Template pomTemplate = ResourceFactory.getTemplate(AsposeWizardResources.POM_FILE_TEMPLATE);
		try(final StringWriter writer = new StringWriter()){
//				Generating the pom.xml file from template ( For template please refer to file "pom.ftl" )
			pomTemplate.process(rootMap, writer);
			IFile file = iProject.getFile("pom.xml");
//				Generating pom.xml file
			file.create(new ByteArrayInputStream(writer.toString().getBytes()),
					IResource.FORCE, null);
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}